package com.iplant.ams.serviceImpl.dao.dms.scada;

import com.iplant.ams.service.basicenum.dms.scada.DMSDataClass;
import com.iplant.ams.service.po.dms.DMSDeviceLedger;
import com.iplant.ams.service.po.dms.scada.record.DMSProcessRecord;
import com.iplant.ams.service.po.dms.scada.record.DMSProcessRecordItem;
import com.iplant.ams.serviceImpl.dao.dms.DMSDeviceLedgerDAO;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.DBEnumType;
import com.iplant.base.po.enums.DBSchemas;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.cache.CacheUtils;
import com.iplant.base.utils.general.CalendarTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.po.bms.BMSEmployee;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
public class DMSProcessRecordDAO extends BaseDAO {

    private static DMSProcessRecordDAO Instance = null;

    private DMSProcessRecordDAO() {
        super("dms_device_processrecord", DBEnumType.MySQL, DBSchemas.AMS);
    }

    public static DMSProcessRecordDAO getInstance() {
        if (Instance == null)
            Instance = new DMSProcessRecordDAO();
        return Instance;
    }


    public List<DMSProcessRecord> DMS_CurrentProcessRecordList(BMSEmployee wLoginUser, int wDeviceID,
                                                               String wDeviceNo, String wAssetNo, String wWorkpieceNo
            , Pagination wPagination, OutResult<Integer> wErrorCode) {
        return DMS_SelectProcessRecordListNew(wLoginUser, -1, -1, "", wAssetNo, wDeviceID, wDeviceNo, wWorkpieceNo, -1,
                null, 1, -1, -1, CalendarTool.getBasicDate(), CalendarTool.getBasicDate(), -1, wPagination, wErrorCode);
    }

    public List<DMSProcessRecord> DMS_UploadProcessRecordList(BMSEmployee wLoginUser, DMSDeviceLedger wDeviceLedger,
                                                              Pagination wPagination, OutResult<Integer> wErrorCode) {


        List<DMSProcessRecord> dmsProcessRecords = DMS_SelectProcessRecordListNew(wLoginUser, -1, -1, "", "",
                wDeviceLedger.ID, "", "", 1,
                StringUtils.parseListArgs(DMSDataClass.TechnologyData.getValue(), DMSDataClass.WorkParams.getValue(),
                        DMSDataClass.QualityParams.getValue()), 1, -1, 0, CalendarTool.getBasicDate(),
                CalendarTool.getBasicDate(), -1, wPagination, wErrorCode);
        if (dmsProcessRecords.size() == 0) {

            this.DMS_UpdateProcessRecordUploadStatus(wLoginUser, wDeviceLedger, 2, 0, wErrorCode);

            dmsProcessRecords = DMS_SelectProcessRecordListNew(wLoginUser, -1, -1, "", "",
                    wDeviceLedger.ID, "", "", 1,
                    StringUtils.parseListArgs(DMSDataClass.TechnologyData.getValue(),
                            DMSDataClass.WorkParams.getValue(), DMSDataClass.QualityParams.getValue()), 1, -1, 0,
                    CalendarTool.getBasicDate(), CalendarTool.getBasicDate(), -1, wPagination,
                    wErrorCode);
        }
        return dmsProcessRecords;
    }


    public void DMS_UpdateProcessRecordUploadStatus(BMSEmployee wLoginUser, List<Integer> wRecordIDList, int wDeviceID,
                                                    String wDeviceNo,
                                                    int wUploadStatus, OutResult<Integer> wErrorCode) {
        wErrorCode.set(0);
        try {
            if (wRecordIDList == null || (wDeviceID <= 0 && StringUtils.isEmpty(wDeviceNo)) || wRecordIDList.size() == 0 || wUploadStatus <= 0)
                return;

            DMSDeviceLedger wDeviceLedger = CacheUtils.GetCacheInfo(DMSDeviceLedger.class, wDeviceID, wDeviceNo);

            if (wDeviceLedger == null || wDeviceLedger.ID <= 0) {
                return;
            }
            this.DMS_UpdateProcessRecordUploadStatus(wLoginUser, wRecordIDList, wDeviceLedger, wUploadStatus,
                    wErrorCode);

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_UpdateProcessRecordUploadStatus", e);
        }
    }


    public void DMS_UpdateProcessRecordUploadStatus(BMSEmployee wLoginUser, List<Integer> wRecordIDList,
                                                    DMSDeviceLedger wDeviceLedger,
                                                    int wUploadStatus, OutResult<Integer> wErrorCode) {

        try {
            wErrorCode.set(0);
            if (wRecordIDList == null || wDeviceLedger == null || wDeviceLedger.ID <= 0 || StringUtils.isEmpty(wDeviceLedger.Code) || wRecordIDList.size() == 0 || wUploadStatus <= 0)
                return;

            wRecordIDList.removeIf(p -> p <= 0);

            wRecordIDList = wRecordIDList.stream().distinct().collect(Collectors.toList());

            if (wRecordIDList.size() == 0)
                return;

            String wTableName = "dms_device_processrecord_" + wDeviceLedger.ChangeToTableName();

            String wSQL = StringUtils.Format(" update {0} t  set t" +
                    ".UploadStatus=:wUploadStatus " +
                    "where  t.UploadStatus!=1 and t.ID in ({1}) ; ", getTableName(wTableName), StringUtils.Join(",",
                    wRecordIDList));


            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wUploadStatus", wUploadStatus);

            this.update(wSQL, wParamMap);

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_UpdateProcessRecordUploadStatus", e);
        }
    }

    public void DMS_UpdateProcessRecordUploadStatus(BMSEmployee wLoginUser,
                                                    DMSDeviceLedger wDeviceLedger, int wOldUploadStatus,
                                                    int wUploadStatus, OutResult<Integer> wErrorCode) {

        try {
            wErrorCode.set(0);
            if (wDeviceLedger == null || wDeviceLedger.ID <= 0 || StringUtils.isEmpty(wDeviceLedger.Code) || StringUtils.isEmpty(wDeviceLedger.AssetNo))
                return;


            String wTableName = "dms_device_processrecord_" + wDeviceLedger.ChangeToTableName();

            String wSQL = StringUtils.Format(" update {0} t  set t" +
                    ".UploadStatus=:wUploadStatus " +
                    "where t.StartTime >= :wMonthTime  and  t.UploadStatus=:wOldUploadStatus and t.ID > 0 and  t" +
                    ".AssetNo=:wAssetNo ; ", getTableName(wTableName));


            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wUploadStatus", wUploadStatus);
            wParamMap.put("wOldUploadStatus", wOldUploadStatus);
            wParamMap.put("wAssetNo", wDeviceLedger.AssetNo);
            wParamMap.put("wMonthTime", CalendarTool.AddCalendar(Calendar.getInstance(), Calendar.MONTH, -1));

            this.update(wSQL, wParamMap);

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_UpdateProcessRecordUploadStatus", e);
        }
    }


    /**
     * 加工记录分表，按设备编号查询
     *
     * @param wLoginUser
     * @param wProductID
     * @param wOrderID
     * @param wOrderNo
     * @param wAssetNo
     * @param wDeviceID
     * @param wDeviceNo
     * @param wWorkpieceNo
     * @param wRecordType
     * @param wDataClassList
     * @param wActive
     * @param wStatus
     * @param wUploadStatus
     * @param wStartTime
     * @param wEndTime
     * @param wTechnologyID
     * @param wPagination
     * @param wErrorCode
     * @return
     */
    public List<DMSProcessRecord> DMS_SelectProcessRecordListNew(BMSEmployee wLoginUser, int wProductID, int wOrderID,
                                                                 String wOrderNo, String wAssetNo, int wDeviceID,
                                                                 String wDeviceNo, String wWorkpieceNo,
                                                                 int wRecordType, List<Integer> wDataClassList,
                                                                 int wActive, int wStatus, int wUploadStatus,
                                                                 Calendar wStartTime, Calendar wEndTime,
                                                                 int wTechnologyID, Pagination wPagination,
                                                                 OutResult<Integer> wErrorCode) {
        List<DMSProcessRecord> wResult = new ArrayList<DMSProcessRecord>();
        wErrorCode.set(0);
        try {

            Calendar wBaseTime = CalendarTool.getBasicDate();
            if (wStartTime.compareTo(wBaseTime) < 0)
                wStartTime = wBaseTime;
            if (wEndTime.compareTo(wBaseTime) < 0)
                wEndTime = wBaseTime;
            if (wStartTime.compareTo(wEndTime) > 0) {
                return wResult;
            }

            if (wOrderNo == null)
                wOrderNo = "";
            if (wDeviceNo == null)
                wDeviceNo = "";


            String wInstance = getDBName();


            String wTableName = "dms_device_processrecord_";


            String wDeviceCode = "";
            DMSDeviceLedger wDMSDeviceLedger = CacheUtils.GetCacheInfo(DMSDeviceLedger.class, wDeviceID, wDeviceNo);

            if (wDMSDeviceLedger == null || wDMSDeviceLedger.ID <= 0) {
                return wResult;
            }


            wDeviceCode = wDMSDeviceLedger.ChangeToTableName();
            int wModelID = wDMSDeviceLedger.ModelID;
            if (wRecordType == 5 && (wModelID == 1 || wModelID == 3))
                wTableName = "dms_device_toolrecord_";
            if (wRecordType == 6 && (wModelID == 4 || wModelID == 5 || wModelID == 7 || wModelID == 8))
                wTableName = "dms_device_toolrecord_";
            wTableName += wDeviceCode;

            if (!this.IsExitTable(getDBName(), wTableName)) {
                return wResult;
            }
            String wSQL = StringUtils.Format("SELECT t.*,o.Code as OrderNo,o.ProductID," +
                            " t1.ID as DeviceID,at1.Name as DeviceName,at1.Code as DeviceNo, t1.ModelID,o.LineID FROM" +
                            " {0}.{1}" +
                            " t" +
                            " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo" +
                            " inner join {0}.ams_asset_list at1 on t1.AssetInfoID = at1.ID" +
                            " left join {2}.oms_order o on t.OrderID = o.ID" +
                            " where t.ID>0 "
                            + " and ( :wOrderID <= 0 or t.OrderID  = :wOrderID)  "
                            + " and ( :wProductID <= 0 or o.ProductID  = :wProductID)  "
                            + " and ( :wOrderNo =''''  or o.Code like :wOrderNo) "
                            + " and ( :wTechnologyID <= 0 or t.TechnologyID  = :wTechnologyID)  "
                            + " and ( :wWorkpieceNo =''''  or t.WorkpieceNo  = :wWorkpieceNo) "
                            + " and ( :wStatus <= 0 or t.Status  = :wStatus)"
                            + " and ( :wUploadStatus < 0 or t.UploadStatus  = :wUploadStatus)"
                            + " and ( :wRecordType <= 0 or t.RecordType  = :wRecordType)"
                            + " and ( :wStartTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')   or :wStartTime <= t" +
                            ".EndTime) "
                            + " and ( :wEndTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')  or :wEndTime >= t" +
                            ".StartTime)  "
                            + " and ( :wActive < 0 or t.Active  = :wActive) ", wInstance, wTableName,
                    DBSchemas.APS.getDBName());


            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wProductID", wProductID);
            wParamMap.put("wOrderID", wOrderID);
            wParamMap.put("wOrderNo", StringUtils.isEmpty(wOrderNo) ? "" : "%" + wOrderNo + "%");
            wParamMap.put("wDeviceID", wDeviceID);
            wParamMap.put("wTechnologyID", wTechnologyID);
            wParamMap.put("wWorkpieceNo", wWorkpieceNo);
            wParamMap.put("wActive", wActive);
            wParamMap.put("wStatus", wStatus);
            wParamMap.put("wStartTime", wStartTime);
            wParamMap.put("wEndTime", wEndTime);
            wParamMap.put("wRecordType", wRecordType);
            wParamMap.put("wAssetNo", wAssetNo);
            wParamMap.put("wUploadStatus", wUploadStatus);


            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap, wPagination);

            if (wQueryResult.size() == 0)
                return wResult;


            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                DMSProcessRecord wProcessRecord = new DMSProcessRecord();

                wProcessRecord.ID = StringUtils.parseInt(wReader.get("ID"));
                wProcessRecord.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wProcessRecord.LineID = StringUtils.parseInt(wReader.get("LineID"));
                wProcessRecord.LineName = StringUtils.parseString(wReader.get("LineName"));
                wProcessRecord.ModelID = StringUtils.parseInt(wReader.get("ModelID"));
                wProcessRecord.DeviceName = StringUtils.parseString(wReader.get("DeviceName"));
                wProcessRecord.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wProcessRecord.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wProcessRecord.SFCOrderID = StringUtils.parseInt(wReader.get("SFCOrderID"));
                wProcessRecord.OrderID = StringUtils.parseInt(wReader.get("OrderID"));
                wProcessRecord.OrderNo = StringUtils.parseString(wReader.get("OrderNo"));
                wProcessRecord.ProductID = StringUtils.parseInt(wReader.get("ProductID"));
                wProcessRecord.MetroNo = StringUtils.parseString(wReader.get("MetroNo"));
                wProcessRecord.WorkpieceNo = StringUtils.parseString(wReader.get("WorkpieceNo"));
                wProcessRecord.StartTime = StringUtils.parseCalendar(wReader.get("StartTime"));
                wProcessRecord.EndTime = StringUtils.parseCalendar(wReader.get("EndTime"));
                wProcessRecord.Active = StringUtils.parseInt(wReader.get("Active"));
                wProcessRecord.Status = StringUtils.parseInt(wReader.get("Status"));
                wProcessRecord.RecordType = StringUtils.parseInt(wReader.get("RecordType"));
                wProcessRecord.RecordType = StringUtils.parseInt(wReader.get("RecordType"));
                wProcessRecord.Remark = StringUtils.parseString(wReader.get("Remark"));
                wProcessRecord.TechnologyID = StringUtils.parseInt(wReader.get("TechnologyID"));
                wResult.add(wProcessRecord);
            }

            if (wDataClassList != null) {

                DMSDataClass wDMSDataClass = DMSDataClass.Default;
                for (int wDataClass : wDataClassList) {
                    wDMSDataClass = DMSDataClass.getEnumType(wDataClass);
                    if (wDMSDataClass == DMSDataClass.Default)
                        continue;
                    if (StringUtils.isNotEmpty(wDeviceCode))
                        this.DMS_SetProcessRecordParamsOld(wLoginUser, wResult, wDMSDataClass, wDeviceCode, wModelID,
                                wRecordType, wErrorCode);
                    else
                        this.DMS_SetProcessRecordParams(wLoginUser, wResult, wDMSDataClass, wErrorCode);

                }
            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecordListNew", e);
        }
        return wResult;
    }

    public List<DMSProcessRecord> DMS_SelectProcessRecordList(BMSEmployee wLoginUser, int wLineID, int wProductID,
                                                              int wOrderID,
                                                              String wOrderNo, String wAssetNo, int wDeviceID,
                                                              String wDeviceNo, String wWorkpieceNo, int wRecordType,
                                                              List<Integer> wDataClassList,
                                                              int wActive, int wStatus, Calendar wStartTime,
                                                              Calendar wEndTime, String wDeviceName,
                                                              int wTechnologyID, int wModelID, Pagination wPagination
            , OutResult<Integer> wErrorCode) {
        List<DMSProcessRecord> wResult = new ArrayList<DMSProcessRecord>();
        try {

            Calendar wBaseTime = CalendarTool.getBasicDate();
            if (wStartTime.compareTo(wBaseTime) < 0)
                wStartTime = wBaseTime;
            if (wEndTime.compareTo(wBaseTime) < 0)
                wEndTime = wBaseTime;
            if (wStartTime.compareTo(wEndTime) > 0) {
                return wResult;
            }

            if (wOrderNo == null)
                wOrderNo = "";
            if (wDeviceNo == null)
                wDeviceNo = "";

            wErrorCode.set(0);
            String wInstance = getDBName();
            String wSQL = StringUtils.Format("SELECT t.*,o.Code as OrderNo,o.LineID,o.ProductID," +
                            " t1.ID as DeviceID,at1.Name as DeviceName,t1.ModelID,l.Name as LineName," +
                            " at1.Code as DeviceNo " +
                            " FROM {0}.dms_device_processrecord t" +
                            " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo" +
                            " inner join {0}.ams_asset_list at1 on t1.AssetInfoID = at1.ID" +
                            " left join {1}.oms_order o on t.OrderID = o.ID" +
                            " left join {2}.fmc_line l on o.LineID = l.ID  " +
                            " where t.ID>0 "
                            + " and ( :wOrderID <= 0 or t.OrderID  = :wOrderID)  "
                            + " and ( :wProductID <= 0 or o.ProductID  = :wProductID)  "
                            + " and ( :wLineID <= 0 or o.LineID  = :wLineID)  "
                            + " and ( :wOrderNo =''''  or o.Code like :wOrderNo) "
                            + " and ( :wAssetNo =''''  or t.AssetNo = :wAssetNo) "
                            + " and ( :wDeviceID <= 0 or t1.ID  = :wDeviceID)  "
                            + " and ( :wModelID <= 0 or t1.ModelID  = :wModelID)  "
                            + " and ( :wTechnologyID <= 0 or t.TechnologyID  = :wTechnologyID)  "
                            + " and ( :wDeviceName =''''  or at1.Name = :wDeviceName) "
                            + " and ( :wDeviceNo =''''  or at1.Code  = :wDeviceNo) "
                            + " and ( :wWorkpieceNo =''''  or t.WorkpieceNo  = :wWorkpieceNo) "
                            + " and ( :wStatus <= 0 or t.Status  = :wStatus)"
                            + " and ( :wRecordType <= 0 or t.RecordType  = :wRecordType)"
                            + " and ( :wStartTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')   or :wStartTime <= t" +
                            ".EndTime) "
                            + " and ( :wEndTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')  or :wEndTime >= t" +
                            ".StartTime)  "
                            + " and ( :wActive < 0 or t.Active  = :wActive) ", wInstance, DBSchemas.APS.getDBName(),
                    DBSchemas.PDM.getDBName());


            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wLineID", wLineID);
            wParamMap.put("wProductID", wProductID);
            wParamMap.put("wOrderID", wOrderID);
            wParamMap.put("wOrderNo", StringUtils.isEmpty(wOrderNo) ? "" : "%" + wOrderNo + "%");
            wParamMap.put("wDeviceID", wDeviceID);
            wParamMap.put("wTechnologyID", wTechnologyID);
            wParamMap.put("wDeviceName", wDeviceName);
            wParamMap.put("wDeviceNo", wDeviceNo);
            wParamMap.put("wModelID", wModelID);
            wParamMap.put("wWorkpieceNo", wWorkpieceNo);
            wParamMap.put("wActive", wActive);
            wParamMap.put("wStatus", wStatus);
            wParamMap.put("wStartTime", wStartTime);
            wParamMap.put("wEndTime", wEndTime);
            wParamMap.put("wRecordType", wRecordType);
            wParamMap.put("wAssetNo", wAssetNo);


            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap, wPagination);

            if (wQueryResult.size() <= 0)
                return wResult;

            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                DMSProcessRecord wProcessRecord = new DMSProcessRecord();

                wProcessRecord.ID = StringUtils.parseInt(wReader.get("ID"));
                wProcessRecord.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wProcessRecord.LineID = StringUtils.parseInt(wReader.get("LineID"));
                wProcessRecord.LineName = StringUtils.parseString(wReader.get("LineName"));
                wProcessRecord.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wProcessRecord.ModelID = StringUtils.parseInt(wReader.get("ModelID"));
                wProcessRecord.DeviceName = StringUtils.parseString(wReader.get("DeviceName"));
                wProcessRecord.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wProcessRecord.SFCOrderID = StringUtils.parseInt(wReader.get("SFCOrderID"));
                wProcessRecord.OrderID = StringUtils.parseInt(wReader.get("OrderID"));
                wProcessRecord.OrderNo = StringUtils.parseString(wReader.get("OrderNo"));
                wProcessRecord.ProductID = StringUtils.parseInt(wReader.get("ProductID"));

                wProcessRecord.MetroNo = StringUtils.parseString(wReader.get("MetroNo"));
                wProcessRecord.WorkpieceNo = StringUtils.parseString(wReader.get("WorkpieceNo"));
                wProcessRecord.StartTime = StringUtils.parseCalendar(wReader.get("StartTime"));
                wProcessRecord.EndTime = StringUtils.parseCalendar(wReader.get("EndTime"));
                wProcessRecord.Active = StringUtils.parseInt(wReader.get("Active"));
                wProcessRecord.Status = StringUtils.parseInt(wReader.get("Status"));
                wProcessRecord.Remark = StringUtils.parseString(wReader.get("Remark"));
                wProcessRecord.TechnologyID = StringUtils.parseInt(wReader.get("TechnologyID"));
                wProcessRecord.RecordType = StringUtils.parseInt(wReader.get("RecordType"));
                wResult.add(wProcessRecord);
            }
            this.DMS_SetProcessRecordItemList(wLoginUser, wResult, wErrorCode);
            if (wDataClassList != null) {

                DMSDataClass wDMSDataClass = DMSDataClass.Default;
                for (int wDataClass : wDataClassList) {
                    wDMSDataClass = DMSDataClass.getEnumType(wDataClass);
                    if (wDMSDataClass == DMSDataClass.Default)
                        continue;
                    this.DMS_SetProcessRecordParams(wLoginUser, wResult, wDMSDataClass, wErrorCode);

                }
            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecordList", e);
        }
        return wResult;
    }

    public List<DMSProcessRecord> DMS_SelectProcessRecordUploadList(BMSEmployee wLoginUser, Pagination wPagination,
                                                                    OutResult<Integer> wErrorCode) {
        List<DMSProcessRecord> wResult = new ArrayList<DMSProcessRecord>();
        try {


            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;


            String wSQL = StringUtils.Format("SELECT t.*,o.Code as OrderNo,o.LineID,o.ProductID," +
                            " t1.ID as DeviceID,at1.Name as DeviceName,l.Name as LineName," +
                            " at1.Code as DeviceNo,d.ProductName,d.ProductNo  FROM {0}.dms_device_processrecord t" +
                            " left join {1}.oms_order o on t.OrderID = o.ID" +
                            " left join {2}.fpc_product d on o.ProductID = d.ID  " +
                            " left join {2}.fmc_line l on o.LineID = l.ID  " +
                            " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo  " +
                            " inner join {0}.ams_asset_list at1 on t1.AssetInfoID = at1.ID" +
                            "  where t.UploadStatus=0 AND t.Active=1  ", wInstance, DBSchemas.APS.getDBName(),
                    DBSchemas.PDM.getDBName());


            Map<String, Object> wParamMap = new HashMap<String, Object>();


            wSQL = this.DMLChange(wSQL);


            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap, wPagination);

            if (wQueryResult.size() <= 0) {
                this.DMS_UpdateProcessRecordUploadStatus(wLoginUser, wErrorCode);
                return wResult;
            }
            List<Integer> wRecordIDList = new ArrayList<Integer>();
            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                DMSProcessRecord wProcessRecord = new DMSProcessRecord();

                wProcessRecord.ID = StringUtils.parseInt(wReader.get("ID"));
                wProcessRecord.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wProcessRecord.LineID = StringUtils.parseInt(wReader.get("LineID"));
                wProcessRecord.LineName = StringUtils.parseString(wReader.get("LineName"));
                wProcessRecord.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wProcessRecord.DeviceName = StringUtils.parseString(wReader.get("DeviceName"));
                wProcessRecord.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wProcessRecord.SFCOrderID = StringUtils.parseInt(wReader.get("SFCOrderID"));
                wProcessRecord.OrderID = StringUtils.parseInt(wReader.get("OrderID"));
                wProcessRecord.OrderNo = StringUtils.parseString(wReader.get("OrderNo"));
                wProcessRecord.ProductID = StringUtils.parseInt(wReader.get("ProductID"));
                wProcessRecord.ProductName = StringUtils.parseString(wReader.get("ProductName"));
                wProcessRecord.ProductNo = StringUtils.parseString(wReader.get("ProductNo"));
                wProcessRecord.MetroNo = StringUtils.parseString(wReader.get("MetroNo"));
                wProcessRecord.WorkpieceNo = StringUtils.parseString(wReader.get("WorkpieceNo"));
                wProcessRecord.StartTime = StringUtils.parseCalendar(wReader.get("StartTime"));
                wProcessRecord.EndTime = StringUtils.parseCalendar(wReader.get("EndTime"));
                wProcessRecord.Active = StringUtils.parseInt(wReader.get("Active"));
                wProcessRecord.Status = StringUtils.parseInt(wReader.get("Status"));
                wProcessRecord.RecordType = StringUtils.parseInt(wReader.get("RecordType"));
                wProcessRecord.Remark = StringUtils.parseString(wReader.get("Remark"));

                wResult.add(wProcessRecord);

                if (wProcessRecord.ID > 0 && !wRecordIDList.contains(wProcessRecord.ID))
                    wRecordIDList.add(wProcessRecord.ID);
            }
            if (wRecordIDList.size() > 0) {
                this.DMS_SetProcessRecordItemList(wLoginUser, wResult, wErrorCode);
                this.DMS_SetProcessRecordParams(wLoginUser, wResult, DMSDataClass.Params, wErrorCode);
                this.DMS_SetProcessRecordParams(wLoginUser, wResult, DMSDataClass.WorkParams, wErrorCode);
                this.DMS_SetProcessRecordParams(wLoginUser, wResult, DMSDataClass.QualityParams, wErrorCode);

                this.DMS_UpdateProcessRecordUploadStatus(wLoginUser, wRecordIDList, 2, wErrorCode);
            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecordUploadList", e);
        }
        return wResult;
    }

    private void DMS_UpdateProcessRecordUploadStatus(BMSEmployee wLoginUser, OutResult<Integer> wErrorCode) {

        try {

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return;

            String wSQL = StringUtils.Format(" update {0}.dms_device_processrecord t  set t.UploadStatus=1 where t" +
                    ".ID>0 AND t.UploadStatus=2; ", wInstance);


            Map<String, Object> wParamMap = new HashMap<String, Object>();

            this.update(wSQL, wParamMap);

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_UpdateProcessRecordUploadStatus", e);
        }
    }


    /**
     * ///
     */
    /// <param name="wLoginUser"></param>
    /// <param name="wRecordIDList"></param>
    /// <param name="wUploadStatus">1上传成功 2 上传失败 0未上传</param>
    /// <param name="wErrorCode"></param>
    public void DMS_UpdateProcessRecordUploadStatus(BMSEmployee wLoginUser, List<Integer> wRecordIDList,
                                                    int wUploadStatus, OutResult<Integer> wErrorCode) {

        try {
            if (wRecordIDList == null || wRecordIDList.size() == 0 || wUploadStatus <= 0)
                return;

            wRecordIDList.removeIf(p -> p <= 0);

            wRecordIDList = wRecordIDList.stream().distinct().collect(Collectors.toList());

            if (wRecordIDList.size() == 0)
                return;


            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return;

            String wSQL = StringUtils.Format(" update {0}.dms_device_processrecord t  set t" +
                    ".UploadStatus=:wUploadStatus " +
                    "where  t.UploadStatus!=1 and t.ID in ({1}) ; ", wInstance, StringUtils.Join(",", wRecordIDList));


            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wUploadStatus", wUploadStatus);

            this.update(wSQL, wParamMap);

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_UpdateProcessRecordUploadStatus", e);
        }
    }

    public DMSProcessRecord DMS_SelectProcessRecord(BMSEmployee wLoginUser, int wRecordID,
                                                    OutResult<Integer> wErrorCode) {

        DMSProcessRecord wResult = new DMSProcessRecord();
        try {
            if (wRecordID <= 0)
                return wResult;

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;
            String wSQL = StringUtils.Format("SELECT t.*,o.Code as OrderNo,o.LineID,o.ProductID," +
                    " t1.ID as DeviceID,at1.Name as DeviceName,l.Name as LineName," +
                    " at1.Code as DeviceNo,d.ProductName,d.ProductNo  FROM {0}.dms_device_processrecord t" +
                    " left join {1}.oms_order o on t.OrderID = o.ID" +
                    " left join {2}.fpc_product d on o.ProductID = d.ID  " +
                    " left join {2}.fmc_line l on o.LineID = l.ID  " +
                    " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo  " +
                    " inner join {0}.ams_asset_list at1 on t1.AssetInfoID = at1.ID" +
                    " where t.ID=:wID ;", wInstance, DBSchemas.APS.getDBName(), DBSchemas.PDM.getDBName());
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wID", wRecordID);
            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);
            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                wResult.ID = StringUtils.parseInt(wReader.get("ID"));
                wResult.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wResult.LineID = StringUtils.parseInt(wReader.get("LineID"));
                wResult.LineName = StringUtils.parseString(wReader.get("LineName"));
                wResult.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wResult.DeviceName = StringUtils.parseString(wReader.get("DeviceName"));
                wResult.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wResult.SFCOrderID = StringUtils.parseInt(wReader.get("SFCOrderID"));
                wResult.OrderID = StringUtils.parseInt(wReader.get("OrderID"));
                wResult.OrderNo = StringUtils.parseString(wReader.get("OrderNo"));
                wResult.ProductID = StringUtils.parseInt(wReader.get("ProductID"));
                wResult.ProductName = StringUtils.parseString(wReader.get("ProductName"));
                wResult.ProductNo = StringUtils.parseString(wReader.get("ProductNo"));
                wResult.MetroNo = StringUtils.parseString(wReader.get("MetroNo"));
                wResult.WorkpieceNo = StringUtils.parseString(wReader.get("WorkpieceNo"));
                wResult.StartTime = StringUtils.parseCalendar(wReader.get("StartTime"));
                wResult.EndTime = StringUtils.parseCalendar(wReader.get("EndTime"));
                wResult.Active = StringUtils.parseInt(wReader.get("Active"));
                wResult.Status = StringUtils.parseInt(wReader.get("Status"));
                wResult.RecordType = StringUtils.parseInt(wReader.get("RecordType"));
                wResult.Remark = StringUtils.parseString(wReader.get("Remark"));
                wResult.ItemList = this.DMS_SelectProcessRecordItemList(wLoginUser, wResult.ID, wErrorCode);

                wResult.ItemList.sort(Comparator.comparingInt(o -> (o.AnalysisOrder <= 0 ? Integer.MAX_VALUE :
                        o.AnalysisOrder)));
            }

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecord", e);
        }
        return wResult;

    }


    public List<DMSProcessRecordItem> DMS_SelectProcessRecordItemList(BMSEmployee wLoginUser, int wRecordID,
                                                                      OutResult<Integer> wErrorCode) {

        List<DMSProcessRecordItem> wResult = new ArrayList<DMSProcessRecordItem>();
        try {
            if (wRecordID <= 0)
                return wResult;


            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;
            String wSQL = StringUtils.Format("SELECT p.* ,t2.DataType,t2.DataClass, t1.AssetNo,t1.ID as DeviceID,t1" +
                    ".Code as DeviceNo," +
                    "  t2.Name as ParameterName,t2.Code as ParameterCode,"
                    + " t2.ParameterDesc,t2.ID AS  ParameterID ,t2.AnalysisOrder FROM {0}.dms_device_recorditem p "
                    + " inner join {0}.dms_device_processrecord t on p.RecordID = t.ID  "
                    + " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo  "
                    + " inner join {0}.dms_device_parameter t2 on t2.Code = p.ParameterNo and t2.DeviceID = t1.ID "
                    + " where t.ID=:wRecordID  ;", wInstance);
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wRecordID", wRecordID);

            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);
            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                DMSProcessRecordItem wProcessRecordItem = new DMSProcessRecordItem();

                wProcessRecordItem.ID = StringUtils.parseLong(wReader.get("ID"));
                wProcessRecordItem.RecordID = StringUtils.parseInt(wReader.get("RecordID"));
                wProcessRecordItem.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wProcessRecordItem.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wProcessRecordItem.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wProcessRecordItem.ParameterID = StringUtils.parseInt(wReader.get("ParameterID"));
                wProcessRecordItem.ParameterNo = StringUtils.parseString(wReader.get("ParameterCode"));
                wProcessRecordItem.ParameterName = StringUtils.parseString(wReader.get("ParameterName"));
                wProcessRecordItem.ParameterDesc = StringUtils.parseString(wReader.get("ParameterDesc"));
                wProcessRecordItem.ParameterValue = StringUtils.parseString(wReader.get("ParameterValue"));
                wProcessRecordItem.DataType = StringUtils.parseInt(wReader.get("DataType"));
                wProcessRecordItem.DataClass = StringUtils.parseInt(wReader.get("DataClass"));
                wProcessRecordItem.AnalysisOrder = StringUtils.parseInt(wReader.get("AnalysisOrder"));
                wProcessRecordItem.SampleTime = StringUtils.parseCalendar(wReader.get("SampleTime"));

                wResult.add(wProcessRecordItem);
            }

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecordItemList", e);
        }
        return wResult;
    }


    private void DMS_SetProcessRecordItemList(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                              OutResult<Integer> wErrorCode) {
        if (wRecordList == null || wRecordList.size() <= 0)
            return;
        List<Integer> wRecordIDList = wRecordList.stream().map(p -> p.ID).collect(Collectors.toList());

        Map<Integer, List<DMSProcessRecordItem>> wDic = this.DMS_SelectProcessRecordItemList(wLoginUser,
                wRecordIDList, wErrorCode);

        for (DMSProcessRecord wDMSProcessRecord : wRecordList) {
            if (wDic.containsKey(wDMSProcessRecord.ID))
                wDMSProcessRecord.ItemList = wDic.get(wDMSProcessRecord);
            if (wDMSProcessRecord.ItemList == null)
                wDMSProcessRecord.ItemList = new ArrayList<DMSProcessRecordItem>();

            wDMSProcessRecord.ItemList.sort((o1, o2) ->
                    (o1.AnalysisOrder <= 0 ? Integer.MAX_VALUE : o1.AnalysisOrder)
                            - (o2.AnalysisOrder <= 0 ? Integer.MAX_VALUE : o2.AnalysisOrder));
        }
    }


    private void DMS_SetProcessRecordParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                            DMSDataClass wDataClass, OutResult<Integer> wErrorCode) {

        List<String> wTableNames = SelectTableNames(getDBName(), wDataClass.GetMysqlTablePrefixString());

        for (String wTableName : wTableNames) {
            switch (wDataClass) {
                case Default:
                    break;
                case Status:
                    break;
                case Alarm:
                    break;
                case Params:
                    //this.DMS_SetProcessRecordTechParams(wLoginUser, wRecordList, wTableName, wErrorCode);
                    break;
                case WorkParams:
                    this.DMS_SetProcessRecordProductParams(wLoginUser, wRecordList, wTableName, wErrorCode);
                    break;
                case PowerParams:
                    break;
                case QualityParams:
                    this.DMS_SetProcessRecordCheckParams(wLoginUser, wRecordList, wTableName, wErrorCode);
                    break;
                case ControlData:
                    break;
                case TechnologyData:
                    this.DMS_SetProcessRecordTechParams(wLoginUser, wRecordList, wTableName, wErrorCode);
                    break;
                case PositionData:
                    break;
                default:
                    break;
            }
        }

    }

    private void DMS_SetProcessRecordParamsOld(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                               DMSDataClass wDataClass, String wDeviceCode, int wModelID,
                                               int wRecordType, OutResult<Integer> wErrorCode) {
        String wTableName = wDataClass.GetMysqlTablePrefixString() + "_" + wDeviceCode;
        if (wRecordType == 1)
            wTableName = wDataClass.GetMysqlTablePrefixString() + "_" + wDeviceCode;
        else if (wRecordType == 5 || wRecordType == 6)
            wTableName = "dms_device_toolparams" + "_" + wDeviceCode;
        switch (wDataClass) {
            case Default:
                break;
            case Status:
                break;
            case Alarm:
                break;
            case Params:
                //this.DMS_SetProcessRecordTechParams(wLoginUser, wRecordList, wTableName, wErrorCode);
                break;
            case WorkParams:
                if (wRecordType == 6)
                    break;
                this.DMS_SetProcessRecordProductParams(wLoginUser, wRecordList, wTableName, wRecordType,
                        wModelID, wErrorCode);
                break;
            case PowerParams:
                break;
            case QualityParams:
                this.DMS_SetProcessRecordCheckParams(wLoginUser, wRecordList, wTableName, wRecordType, wModelID
                        , wErrorCode);
                break;
            case ControlData:
                break;
            case TechnologyData:
                this.DMS_SetProcessRecordTechParams(wLoginUser, wRecordList, wTableName, wErrorCode);
                break;
            case PositionData:
                break;
            default:
                break;
        }

    }

    private void DMS_SetProcessRecordCheckParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                                 String wTableName, OutResult<Integer> wErrorCode) {
        try {
            if (wRecordList == null || wRecordList.size() == 0)
                return;
            Map<Integer, List<DMSProcessRecord>> wRecordIDList =
                    wRecordList.stream().collect(Collectors.groupingBy(p -> p.ID));


            String wInstance = getDBName();

            List<Map<String, Object>> wQueryTableResult = this.queryForList(
                    StringUtils.Format("SELECT * FROM information_schema.TABLES where table_name=''{1}'' and " +
                            "TABLE_SCHEMA =''{0}'';", wInstance, wTableName), null);
            if (wQueryTableResult.size() == 0)
                return;

            //根据加工类型，筛选返回字段
            List<Map<String, Object>> wQueryResult = this.queryForList(
                    StringUtils.Format("select * From {0}.{1} where RecordID IN ({2})", wInstance, wTableName,
                            StringUtils.Join(",", wRecordIDList.keySet())), null);

            int wRecordID = 0;
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey("RecordID"))
                    continue;
                wRecordID = StringUtils.parseInt(wReader.get("RecordID"));
                if (!wRecordIDList.containsKey(wRecordID))
                    continue;

                wReader.remove("RecordID");
                if (!wReader.containsKey("ID"))
                    wReader.remove("ID");

                wRecordIDList.get(wRecordID).forEach(p -> {
                    if (p.CheckParams.size() > 0) {
                        wReader.keySet().forEach(q -> {
                            if (p.CheckParams.containsKey(q) && StringUtils.isNotEmpty(p.CheckParams.get(q).toString())) {
                                p.CheckParams.put(q,
                                        StringUtils.parseString(p.CheckParams.get(q)) + "," + StringUtils.parseString(wReader.get(q)));
                            } else {
                                p.CheckParams.put(q, wReader.get(q));
                            }
                        });
                    } else {
                        p.CheckParams.putAll(wReader);
                    }
                });
            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SetProcessRecordCheckParams", e);
        }
    }

    private void DMS_SetProcessRecordCheckParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                                 String wTableName, int wRecordType, int wModelID,
                                                 OutResult<Integer> wErrorCode) {
        try {
            if (wRecordList == null || wRecordList.size() <= 0)
                return;
            Map<Integer, List<DMSProcessRecord>> wRecordIDList =
                    wRecordList.stream().collect(Collectors.groupingBy(p -> p.ID));

            List<Map<String, Object>> wQueryResult = new ArrayList<Map<String, Object>>();

            String wInstance = getDBName();

            List<Map<String, Object>> wQueryTableResult = this.queryForList(
                    StringUtils.Format("SELECT * FROM information_schema.TABLES where table_name=''{1}'' and " +
                            "TABLE_SCHEMA =''{0}'';", wInstance, wTableName), null);
            if (wQueryTableResult.size() <= 0)
                return;

            //根据加工类型，筛选返回字段
            if (wRecordType == 1)
                wQueryResult = this.queryForList(
                        StringUtils.Format("select * From {0}.{1} where RecordID IN ({2})", wInstance, wTableName,
                                StringUtils.Join(",", wRecordIDList.keySet())), null);
            else if (wRecordType == 6) {
                if (wModelID == 4)
                    wQueryResult = this.queryForList(
                            StringUtils.Format("select RecordID,`5018` From {0}.{1} where RecordID IN ({2})",
                                    wInstance, wTableName, StringUtils.Join(",", wRecordIDList.keySet())), null);
                else if (wModelID == 5)
                    wQueryResult = this.queryForList(
                            StringUtils.Format("select RecordID,`4015` From {0}.{1} where RecordID IN ({2})",
                                    wInstance, wTableName, StringUtils.Join(",", wRecordIDList.keySet())), null);
                else if (wModelID == 7 || wModelID == 8)
                    wQueryResult = this.queryForList(
                            StringUtils.Format("select RecordID,`8006` From {0}.{1} where RecordID IN ({2})",
                                    wInstance, wTableName, StringUtils.Join(",", wRecordIDList.keySet())), null);
            }


            int wRecordID = 0;
            if (wModelID == 4 && wRecordType == 1) {
                for (Map<String, Object> wReader : wQueryResult) {
                    if (!wReader.containsKey("RecordID"))
                        continue;
                    wRecordID = StringUtils.parseInt(wReader.get("RecordID"));
                    if (!wRecordIDList.containsKey(wRecordID))
                        continue;

                    wReader.remove("RecordID");
                    if (!wReader.containsKey("ID"))
                        wReader.remove("ID");

                    wRecordIDList.get(wRecordID).forEach(p -> p.CheckParams.putAll(wReader));

                }
                return;
            }
            if (wModelID == 5 && wRecordType == 1) {
                for (Map<String, Object> wReader : wQueryResult) {
                    if (!wReader.containsKey("RecordID"))
                        continue;
                    wRecordID = StringUtils.parseInt(wReader.get("RecordID"));
                    if (!wRecordIDList.containsKey(wRecordID))
                        continue;

                    wReader.remove("RecordID");
                    if (!wReader.containsKey("ID"))
                        wReader.remove("ID");
                    wRecordIDList.get(wRecordID).forEach(p -> p.CheckParams.putAll(wReader));

                }
                return;
            }
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey("RecordID"))
                    continue;
                wRecordID = StringUtils.parseInt(wReader.get("RecordID"));
                if (!wRecordIDList.containsKey(wRecordID))
                    continue;

                wReader.remove("RecordID");
                if (!wReader.containsKey("ID"))
                    wReader.remove("ID");


                wRecordIDList.get(wRecordID).forEach(p -> {
                    if (p.CheckParams.size() > 0) {
                        wReader.keySet().forEach(q -> {
                            if (p.CheckParams.containsKey(q) && StringUtils.isNotEmpty(p.CheckParams.get(q).toString())) {
                                p.CheckParams.put(q,
                                        StringUtils.parseString(p.CheckParams.get(q)) + "," + StringUtils.parseString(wReader.get(q)));
                            } else {
                                p.CheckParams.put(q, wReader.get(q));
                            }
                        });
                    } else {
                        p.CheckParams.putAll(wReader);
                    }
                });

            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SetProcessRecordCheckParams", e);
        }
    }

    private void DMS_SetProcessRecordProductParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                                   String wTableName, OutResult<Integer> wErrorCode) {
        try {
            if (wRecordList == null || wRecordList.size() <= 0)
                return;
            Map<Integer, List<DMSProcessRecord>> wRecordIDList =
                    wRecordList.stream().collect(Collectors.groupingBy(p -> p.ID));

            String wInstance = getDBName();
            List<Map<String, Object>> wQueryTableResult = this.queryForList(
                    StringUtils.Format("SELECT * FROM information_schema.TABLES where table_name=''{1}'' and " +
                            "TABLE_SCHEMA =''{0}'';", wInstance, wTableName), null);
            if (wQueryTableResult.size() <= 0)
                return;

            List<Map<String, Object>> wQueryResult = this.queryForList(StringUtils.Format("select * From {0}.{1} " +
                            "where RecordID IN ({2})", wInstance, wTableName, StringUtils.Join(",",
                            wRecordIDList.keySet())),
                    null);

            int wRecordID = 0;
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey("RecordID"))
                    continue;
                wRecordID = StringUtils.parseInt(wReader.get("RecordID"));
                if (!wRecordIDList.containsKey(wRecordID))
                    continue;

                wReader.remove("RecordID");
                if (!wReader.containsKey("ID"))
                    wReader.remove("ID");


                wRecordIDList.get(wRecordID).forEach(p -> {
                    if (p.ProductParams.size() > 0) {
                        wReader.keySet().forEach(q -> {
                            if (p.ProductParams.containsKey(q) && StringUtils.isNotEmpty(p.ProductParams.get(q).toString())) {
                                p.ProductParams.put(q,
                                        StringUtils.parseString(p.ProductParams.get(q)) + "," + StringUtils.parseString(wReader.get(q)));
                            } else {
                                p.ProductParams.put(q, wReader.get(q));
                            }
                        });
                    } else {
                        p.ProductParams.putAll(wReader);
                    }
                });

            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SetProcessRecordProductParams", e);
        }
    }

    private void DMS_SetProcessRecordProductParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                                   String wTableName, int wRecordType, int wModelID,
                                                   OutResult<Integer> wErrorCode) {
        try {
            if (wRecordList == null || wRecordList.size() <= 0)
                return;
            Map<Integer, List<DMSProcessRecord>> wRecordIDList =
                    wRecordList.stream().collect(Collectors.groupingBy(p -> p.ID));
            List<Map<String, Object>> wQueryResult = new ArrayList<Map<String, Object>>();


            String wInstance = getDBName();
            List<Map<String, Object>> wQueryTableResult = this.queryForList(
                    StringUtils.Format("SELECT * FROM information_schema.TABLES where table_name=''{1}'' and " +
                            "TABLE_SCHEMA =''{0}'';", wInstance, wTableName), null);
            if (wQueryTableResult.size() <= 0)
                return;

            //根据加工类型，筛选返回字段
            if (wRecordType == 5 && (wModelID == 1 || wModelID == 3)) {
                wQueryResult = this.queryForList(
                        StringUtils.Format("select RecordID,`3014`,`3016`,`3020` From {0}.{1} where RecordID IN ({2})"
                                , wInstance, wTableName, StringUtils.Join(",", wRecordIDList.keySet())), null);
            } else {
                wQueryResult = this.queryForList(
                        StringUtils.Format("select * From {0}.{1} where RecordID IN ({2})", wInstance, wTableName,
                                StringUtils.Join(",", wRecordIDList.keySet())), null);
            }

            int wRecordID = 0;
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey("RecordID"))
                    continue;
                wRecordID = StringUtils.parseInt(wReader.get("RecordID"));
                if (!wRecordIDList.containsKey(wRecordID))
                    continue;


                wReader.remove("RecordID");
                if (!wReader.containsKey("ID"))
                    wReader.remove("ID");

                wRecordIDList.get(wRecordID).forEach(p -> {
                    if (p.ProductParams.size() > 0) {
                        wReader.keySet().forEach(q -> {
                            if (p.ProductParams.containsKey(q) && StringUtils.isNotEmpty(p.ProductParams.get(q).toString())) {
                                p.ProductParams.put(q,
                                        StringUtils.parseString(p.ProductParams.get(q)) + "," + StringUtils.parseString(wReader.get(q)));
                            } else {
                                p.ProductParams.put(q, wReader.get(q));
                            }
                        });
                    } else {
                        p.ProductParams.putAll(wReader);
                    }
                });
            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SetProcessRecordProductParams", e);
        }
    }

    //private void DMS_SetProcessRecordTechParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
    // OutResult<Integer> wErrorCode)
    //{
    //    try
    //    {
    //        if (wRecordList == null || wRecordList.size() <= 0)
    //            return;
    //        Map<Integer, List<DMSProcessRecord>> wRecordIDList = wRecordList.GroupBy(p -> p.TechnologyID)
    //        .ToDictionary(p -> p.Key, p -> p.ToList());


    //        String wInstance = getDBName();

    //        List<Map<String, Object>> wQueryResult = this.queryForList(StringUtils.Format("select * From {0}
    //        .dms_technology where RecordID IN ({1})", wInstance, StringUtils.Join(",", wRecordIDList.keySet())),
    //        null);

    //        int wRecordID = 0;
    //        for (Map<String, Object> wReader : wQueryResult)
    //        {
    //            if (!wReader.containsKey("ID"))
    //                continue;
    //            wRecordID = StringUtils.parseInt(wReader.get("ID"));
    //            if (!wRecordIDList.containsKey(wRecordID))
    //                continue;

    //            wReader.remove("RecordID");
    //            if (!wReader.containsKey("ID"))
    //                wReader.remove("ID");
    //            wRecordIDList.get(wRecordID).forEach(p -> p.ProductParams = wReader);

    //        }
    //    }
    //    catch (Exception e)
    //    {
    //        wErrorCode.set(ExceptionTypes.DBSQL.getValue());
    //        log.error("DMS_SetProcessRecordTechParams", e);
    //    }
    //}
    private void DMS_SetProcessRecordTechParams(BMSEmployee wLoginUser, List<DMSProcessRecord> wRecordList,
                                                String wTableName, OutResult<Integer> wErrorCode) {
        try {
            if (wRecordList == null || wRecordList.size() <= 0)
                return;
            Map<Integer, List<DMSProcessRecord>> wTechnologyIDList =
                    wRecordList.stream().collect(Collectors.groupingBy(p -> p.TechnologyID));

            String wInstance = getDBName();
            List<Map<String, Object>> wQueryTableResult = this.queryForList(
                    StringUtils.Format("SELECT * FROM information_schema.TABLES where table_name=''{1}'' and " +
                            "TABLE_SCHEMA =''{0}'';", wInstance, wTableName), null);
            if (wQueryTableResult.size() <= 0)
                return;
            List<Map<String, Object>> wQueryResult = this.queryForList(StringUtils.Format("select * From {0}.{1} " +
                            "where ID IN ({2})", wInstance, wTableName, StringUtils.Join(",",
                            wTechnologyIDList.keySet())),
                    null);

            int wTechnologyID = 0;
            for (Map<String, Object> wReader : wQueryResult) {
                if (!wReader.containsKey("ID"))
                    continue;
                wTechnologyID = StringUtils.parseInt(wReader.get("ID"));
                if (!wTechnologyIDList.containsKey(wTechnologyID))
                    continue;

                wReader.remove("ID");
                wTechnologyIDList.get(wTechnologyID).forEach(p -> p.TechnologyParams.putAll(wReader));

            }
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SetProcessRecordTechParams", e);
        }
    }


    private Map<Integer, List<DMSProcessRecordItem>> DMS_SelectProcessRecordItemList(BMSEmployee wLoginUser,
                                                                                     List<Integer> wRecordIDList,
                                                                                     OutResult<Integer> wErrorCode) {

        Map<Integer, List<DMSProcessRecordItem>> wResult = new HashMap<Integer, List<DMSProcessRecordItem>>();
        try {
            if (wRecordIDList == null)
                return wResult;

            wRecordIDList.removeIf(p -> p <= 0);

            wRecordIDList = wRecordIDList.stream().distinct().collect(Collectors.toList());

            if (wRecordIDList.size() == 0)
                return wResult;

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;
            String wSQL = StringUtils.Format("SELECT P.* ,t2.DataType,t2.DataClass, t1.AssetNo,t1.ID as DeviceID,t1" +
                    ".Code as DeviceNo ,t2.Name as ParameterName,"
                    + " t2.ParameterDesc,t2.ID  AS  ParameterID ,t2.AnalysisOrder FROM {0}.dms_device_recorditem p "
                    + " inner join {0}.dms_device_processrecord t on p.RecordID = t.ID  "
                    + " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo  "
                    + " inner join {0}.dms_device_parameter t2 on t2.Code = p.ParameterNo and t2.DeviceID = t1.ID "
                    + " where t.ID in ({1})  ;", wInstance, StringUtils.Join(",", wRecordIDList));
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();


            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);
            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                DMSProcessRecordItem wProcessRecordItem = new DMSProcessRecordItem();

                wProcessRecordItem.ID = StringUtils.parseLong(wReader.get("ID"));
                wProcessRecordItem.RecordID = StringUtils.parseInt(wReader.get("RecordID"));
                wProcessRecordItem.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wProcessRecordItem.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wProcessRecordItem.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wProcessRecordItem.ParameterID = StringUtils.parseInt(wReader.get("ParameterID"));
                wProcessRecordItem.ParameterNo = StringUtils.parseString(wReader.get("ParameterNo"));
                wProcessRecordItem.ParameterName = StringUtils.parseString(wReader.get("ParameterName"));
                wProcessRecordItem.ParameterDesc = StringUtils.parseString(wReader.get("ParameterDesc"));
                wProcessRecordItem.ParameterValue = StringUtils.parseString(wReader.get("ParameterValue"));
                wProcessRecordItem.DataType = StringUtils.parseInt(wReader.get("DataType"));
                wProcessRecordItem.DataClass = StringUtils.parseInt(wReader.get("DataClass"));
                wProcessRecordItem.AnalysisOrder = StringUtils.parseInt(wReader.get("AnalysisOrder"));
                wProcessRecordItem.SampleTime = StringUtils.parseCalendar(wReader.get("SampleTime"));

                if (!wResult.containsKey(wProcessRecordItem.RecordID))
                    wResult.put(wProcessRecordItem.RecordID, new ArrayList<DMSProcessRecordItem>());
                wResult.get(wProcessRecordItem.RecordID).add(wProcessRecordItem);
            }

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecordItemList", e);
        }
        return wResult;
    }


    public List<DMSProcessRecordItem> DMS_SelectProcessRecordItemList(BMSEmployee wLoginUser, int wDeviceID,
                                                                      String wDeviceNo, int wRecordID,
                                                                      int wParameterID, String wParameterNo,
                                                                      int wActive, int wStatus, Calendar wStartTime,
                                                                      Calendar wEndTime, Pagination wPagination,
                                                                      OutResult<Integer> wErrorCode) {

        List<DMSProcessRecordItem> wResult = new ArrayList<DMSProcessRecordItem>();
        try {
            Calendar wBaseTime = CalendarTool.getBasicDate();
            if (wStartTime.compareTo(wBaseTime) < 0)
                wStartTime = wBaseTime;
            if (wEndTime.compareTo(wBaseTime) < 0)
                wEndTime = wBaseTime;
            if (wStartTime.compareTo(wEndTime) > 0) {
                return wResult;
            }

            if (wDeviceID <= 0 || StringUtils.isEmpty(wDeviceNo)) {
                return wResult;
            }


            if (wParameterNo == null)
                wParameterNo = "";
            if (wDeviceNo == null)
                wDeviceNo = "";


            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;
            String wSQL = StringUtils.Format("SELECT p.* ,t2.DataType,t2.DataClass,t1.AssetNo, t1.ID as DeviceID ,t1" +
                    ".Code as DeviceNo ,t2.Name as ParameterName,"
                    + " t2.ParameterDesc,t2.ID as  ParameterID ,t2.AnalysisOrder  FROM {0}.dms_device_recorditem p "
                    + " inner join {0}.dms_device_processrecord t on p.RecordID = t.ID  "
                    + " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo  "
                    + " inner join {0}.dms_device_parameter t2 on t2.Code = p.ParameterNo and t2.DeviceID = t1.ID "
                    + " where 1=1 "
                    + " and ( :wRecordID <= 0 or t.ID  = :wRecordID)  "
                    + " and ( :wDeviceID <= 0 or t1.ID  = :wDeviceID)  "
                    + " and ( :wDeviceNo =''''  or t1.Code  = :wDeviceNo) "
                    + " and ( :wParameterID <= 0 or t2.ID  = :wParameterID)  "
                    + " and ( :wParameterNo =''''  or p.ParameterNo  = :wParameterNo) "
                    + " and ( :wStatus <= 0 or t.Status  = :wStatus)"
                    + " and ( :wStartTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')   or :wStartTime <= t.EndTime) "
                    + " and ( :wEndTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')  or :wEndTime >= t.StartTime)  "
                    + " and ( :wActive < 0 or t.Active  = :wActive) ", wInstance);
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wRecordID", wRecordID);
            wParamMap.put("wDeviceID", wDeviceID);
            wParamMap.put("wDeviceNo", wDeviceNo);
            wParamMap.put("wParameterID", wParameterID);
            wParamMap.put("wParameterNo", wParameterNo);
            wParamMap.put("wStatus", wStatus);
            wParamMap.put("wActive", wActive);
            wParamMap.put("wStartTime", wStartTime);
            wParamMap.put("wEndTime", wEndTime);

            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap, wPagination);
            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                DMSProcessRecordItem wProcessRecordItem = new DMSProcessRecordItem();

                wProcessRecordItem.ID = StringUtils.parseLong(wReader.get("ID"));
                wProcessRecordItem.RecordID = StringUtils.parseInt(wReader.get("RecordID"));
                wProcessRecordItem.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wProcessRecordItem.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wProcessRecordItem.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wProcessRecordItem.ParameterID = StringUtils.parseInt(wReader.get("ParameterID"));
                wProcessRecordItem.ParameterNo = StringUtils.parseString(wReader.get("ParameterNo"));
                wProcessRecordItem.ParameterName = StringUtils.parseString(wReader.get("ParameterName"));
                wProcessRecordItem.ParameterDesc = StringUtils.parseString(wReader.get("ParameterDesc"));
                wProcessRecordItem.ParameterValue = StringUtils.parseString(wReader.get("ParameterValue"));
                wProcessRecordItem.DataType = StringUtils.parseInt(wReader.get("DataType"));
                wProcessRecordItem.DataClass = StringUtils.parseInt(wReader.get("DataClass"));
                wProcessRecordItem.AnalysisOrder = StringUtils.parseInt(wReader.get("AnalysisOrder"));
                wProcessRecordItem.SampleTime = StringUtils.parseCalendar(wReader.get("SampleTime"));

                wResult.add(wProcessRecordItem);
            }

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectProcessRecordItemList", e);
        }
        return wResult;
    }


    /**
     * /// 某时间段内，设备过程数据没有订单的记录自动绑定此订单信息
     */
    /// <param name="wLoginUser"></param>
    /// <param name="wAssetNo"></param>
    /// <param name="wOrderNo"></param>
    /// <param name="wStartTime"></param>
    /// <param name="wEndTime"></param>
    public void DMS_UpdateProcessRecordOrder(BMSEmployee wLoginUser, String wAssetNo, int wOrderID,
                                             Calendar wStartTime, Calendar wEndTime, OutResult<Integer> wErrorCode) {
        try {
            String wInstance = getDBName();


            String wSQL = StringUtils.Format("update {0}.dms_device_processrecord set OrderID=:wOrderID " +
                            " where ID>0 AND AssetNo=:wAssetNo AND OrderNo=''''  AND StartTime>= :wStartTime   AND   " +
                            "EndTime <= :wEndTime ; ",
                    wInstance);

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wAssetNo", wAssetNo);
            wParamMap.put("wOrderID", wOrderID);
            wParamMap.put("wStartTime", wStartTime);
            wParamMap.put("wEndTime", wEndTime);

            this.update(wSQL, wParamMap);
        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_UpdateProcessRecordOrder", e);
        }
    }


    /**
     * /// 插入过程记录
     */
    /// <param name="wLoginUser"></param>
    /// <param name="wDMSProcessRecord"></param>
    /// <param name="wErrorCode"></param>
    public void DMS_InsertProcessRecord(BMSEmployee wLoginUser, DMSProcessRecord wDMSProcessRecord,
                                        OutResult<Integer> wErrorCode) {

        try {
            if (wDMSProcessRecord == null || StringUtils.isEmpty(wDMSProcessRecord.AssetNo))
                return;
            wErrorCode.set(0);
            String wInstance = getDBName();


            if (wDMSProcessRecord.Status == 0)
                wDMSProcessRecord.Status = 1;

            String wSQL = StringUtils.Format("update {0}.dms_device_processrecord set Active=0,EditTime=now() " +
                            " where AssetNo=:wAssetNo  AND WorkpieceNo = :wWorkpieceNo AND Active = 1  ; ",
                    wInstance);
            Map<String, Object> wParamMap = new HashMap<String, Object>();


            wParamMap.put("wAssetNo", wDMSProcessRecord.AssetNo);
            // wParamMap.put("wOrderNo", wDMSProcessRecord.OrderNo);
            wParamMap.put("wOrderID", wDMSProcessRecord.OrderID);
            wParamMap.put("wMetroNo", wDMSProcessRecord.MetroNo);
            wParamMap.put("wWorkpieceNo", wDMSProcessRecord.WorkpieceNo);
            wParamMap.put("wStartTime", wDMSProcessRecord.StartTime);
            wParamMap.put("wEndTime", wDMSProcessRecord.EndTime);
            wParamMap.put("wStatus", wDMSProcessRecord.Status);
            wParamMap.put("wRemark", wDMSProcessRecord.Remark);
            wParamMap.put("wRecordType", wDMSProcessRecord.RecordType);

            int wRowChange = this.update(wSQL, wParamMap);

            wSQL = StringUtils.Format("Insert into {0}.dms_device_processrecord (AssetNo,OrderID,MetroNo,WorkpieceNo," +
                            "StartTime,EndTime,Active,Status,Remark,EditTime,RecordType) values " +
                            " (:wAssetNo,:wOrderID,:wMetroNo,:wWorkpieceNo,:wStartTime,:wEndTime,1,:wStatus,:wRemark," +
                            "now(),:wRecordType) ; ",
                    wInstance);


            DMSDeviceLedger wDMSDeviceLedger = DMSDeviceLedgerDAO.getInstance().DMS_SelectDeviceLedger(wLoginUser, 0,
                    "", wDMSProcessRecord.AssetNo, wErrorCode);
            if (wErrorCode.Result != 0)
                return;
            if (wDMSDeviceLedger == null || wDMSDeviceLedger.ID < 0) {
                wErrorCode.Result = ExceptionTypes.Parameter.getValue();
                return;
            }

            wDMSProcessRecord.ID = ((int) this.insert(wSQL, wParamMap));

            if (wDMSProcessRecord.ID <= 0) {
                wErrorCode.Result = ExceptionTypes.Exception.getValue();
                return;
            }
            if (wDMSProcessRecord.ItemList != null && wDMSProcessRecord.ItemList.size() > 0) {
                this.DMS_InsertProcessRecordItemList(wLoginUser, wDMSProcessRecord.ItemList, wDMSProcessRecord.ID,
                        wErrorCode);
            }

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_InsertProcessRecord", e);
        }
    }

    /**
     * /// 获取记录类型对应的最后一次结果
     */
    /// <param name="wLoginUser"></param>
    /// <param name="wWorkpieceNo"></param>
    /// <param name="wErrorCode"></param>
    /// <returns></returns>
    public DMSProcessRecord DMS_SelectLastRecord(BMSEmployee wLoginUser, String wWorkpieceNo, int wRecordType,
                                                 OutResult<Integer> wErrorCode) {

        DMSProcessRecord wResult = new DMSProcessRecord();
        try {
            if (StringUtils.isEmpty(wWorkpieceNo))
                return wResult;

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;
            String wSQL = StringUtils.Format("SELECT t.*,o.Code as OrderNo,t1.ID as DeviceID," +
                    " at1.Name as DeviceName,at1.Code as DeviceNo  FROM {0}.dms_device_processrecord t" +
                    " inner join {1}.oms_order o on t.OrderID = o.ID" +
                    " inner join {0}.dms_device_ledger t1 on t.AssetNo = t1.AssetNo" +
                    " inner join {0}.ams_asset_list at1 on t1.AssetInfoID = at1.ID" +
                    " where t.WorkpieceNo=:wWorkpieceNo and (:wRecordType<=0 or t.RecordType=:wRecordType) order by " +
                    "ID desc limit 1;", wInstance, DBSchemas.APS.getDBName());
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("wWorkpieceNo", wWorkpieceNo);
            wParamMap.put("wRecordType", wRecordType);
            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);
            // wReader\[\"(\w+)\"\]
            for (Map<String, Object> wReader : wQueryResult) {
                wResult.ID = StringUtils.parseInt(wReader.get("ID"));
                wResult.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wResult.DeviceNo = StringUtils.parseString(wReader.get("DeviceNo"));
                wResult.DeviceName = StringUtils.parseString(wReader.get("DeviceName"));
                wResult.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wResult.SFCOrderID = StringUtils.parseInt(wReader.get("SFCOrderID"));
                wResult.OrderID = StringUtils.parseInt(wReader.get("OrderID"));
                wResult.OrderNo = StringUtils.parseString(wReader.get("OrderNo"));
                wResult.MetroNo = StringUtils.parseString(wReader.get("MetroNo"));
                wResult.WorkpieceNo = StringUtils.parseString(wReader.get("WorkpieceNo"));
                wResult.MetroNo = StringUtils.parseString(wReader.get("MetroNo"));
                wResult.StartTime = StringUtils.parseCalendar(wReader.get("StartTime"));
                wResult.EndTime = StringUtils.parseCalendar(wReader.get("EndTime"));
                wResult.Active = StringUtils.parseInt(wReader.get("Active"));
                wResult.Status = StringUtils.parseInt(wReader.get("Status"));
                wResult.Remark = StringUtils.parseString(wReader.get("Remark"));
            }

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_SelectLastRecord", e);
        }
        return wResult;
    }


    public void DMS_InsertProcessRecordItemList(BMSEmployee wLoginUser,
                                                List<DMSProcessRecordItem> wDMSProcessRecordItemList, int wRecordID,
                                                OutResult<Integer> wErrorCode) {
        try {
            if (wRecordID <= 0 || wDMSProcessRecordItemList == null || wDMSProcessRecordItemList.size() <= 0) {
                return;
            }

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return;

            List<String> wValueStringList = new ArrayList<String>();

            String wValueTemp = "({0},''{1}'',''{2}'',''{3}'')";

            for (DMSProcessRecordItem wDMSProcessRecordItem : wDMSProcessRecordItemList) {
                if (wDMSProcessRecordItem == null || StringUtils.isEmpty(wDMSProcessRecordItem.ParameterNo))
                    continue;


                if (wDMSProcessRecordItem.SampleTime.get(Calendar.YEAR) <= 2010)
                    wDMSProcessRecordItem.SampleTime = Calendar.getInstance();

                if (wDMSProcessRecordItem.ParameterValue == null)
                    wDMSProcessRecordItem.ParameterValue = "";

                wValueStringList.add(StringUtils.Format(wValueTemp, wRecordID, wDMSProcessRecordItem.ParameterNo,
                        wDMSProcessRecordItem.ParameterValue,
                        StringUtils.parseCalendarToString(wDMSProcessRecordItem.SampleTime, "yyyy-MM-dd HH:mm:ss")));
            }


            String wSQL = StringUtils.Format("insert into {0}.dms_device_recorditem (RecordID,ParameterNo," +
                    "ParameterValue,SampleTime) Values ", wInstance)
                    + StringUtils.Join(",", wValueStringList);


            this.update(wSQL, new HashMap<String, Object>());

        } catch (Exception e) {
            wErrorCode.set(ExceptionTypes.DBSQL.getValue());
            log.error("DMS_InsertProcessRecordItemList", e);
        }
    }


    /**
     * 更新备注
     */
    public void DMS_UpdateProcessRecordRemark(BMSEmployee wLoginUser, DMSDeviceLedger dmsDeviceLedger,
                                              DMSProcessRecord dmsProcessRecord) {
        try {
            if (dmsProcessRecord == null || dmsProcessRecord.ID <= 0) {
                return;
            }

            String wTableName = "dms_device_processrecord_" + dmsDeviceLedger.ChangeToTableName();

            String wSQL = StringUtils.Format(" update {0} t  set t" +
                    ".Remark=:Remark " +
                    "where t.ID = :ID ; ", getTableName(wTableName), StringUtils.Join(","));

            Map<String, Object> wParamMap = new HashMap<String, Object>();

            wParamMap.put("Remark", dmsProcessRecord.Remark);
            wParamMap.put("ID", dmsProcessRecord.ID);

            wSQL = this.DMLChange(wSQL);

            this.update(wSQL, wParamMap);
        } catch (Exception ex) {
            log.error("DMS_UpdateProcessRecordRemark", ex);
        }
    }
}
